using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;

namespace Ease.EaseNode.Editor.NodeView
{
    public abstract class BaseSoInspectorView<TSo> : VisualElement, IInspectorView where TSo : ScriptableObject
    {
        UnityEditor.Editor editor;
        protected TSo so = null;

        public void OnEnable()
        {
            CreateEditor();
            EditorApplication.playModeStateChanged -= OnPlayModeChange;
            EditorApplication.playModeStateChanged += OnPlayModeChange;
        }

        public void OnDisable()
        {
            so = null;
            Clear();
            EditorApplication.playModeStateChanged -= OnPlayModeChange;
        }

        protected virtual void CreateEditor()
        {
            Clear();
            so = ScriptableObject.CreateInstance<TSo>();
            editor = UnityEditor.Editor.CreateEditor(so);
            var container = new IMGUIContainer(() => { editor.OnInspectorGUI(); });
            Add(container);
        }

        private void OnPlayModeChange(PlayModeStateChange stateChange)
        {
            //离开Play模式;
            if (stateChange == PlayModeStateChange.ExitingPlayMode)
            {
                OnExitingPlayMode();
            }
            //进入Eidtor模式;
            else if (stateChange == PlayModeStateChange.EnteredEditMode)
            {
                OnEnteredEditorMode();
            }
        }

        protected virtual void OnExitingPlayMode()
        {
            Clear();
        }

        protected virtual void OnEnteredEditorMode()
        {
            CreateEditor();
        }
    }
}